package com.li.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.li.constant.MessageConstant;
import com.li.entity.Result;
import com.li.pojo.Member;
import com.li.service.MemberService;
import com.li.utils.DateUtils;
import com.li.utils.RedisMessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    JedisPool jedisPool;
    @Reference
    MemberService memberService;
    @RequestMapping("/login4Message")
    public Result login4Message(@RequestBody Map map, HttpServletResponse response) throws Exception {
        //通过短信登录
        //获取手机号和验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        //比对验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if(codeInRedis==null||!validateCode.equals(codeInRedis)){
            //验证码有误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //验证码正确 判断当前用户是否是会员
        Member member = memberService.findMemberByPhone(telephone);
        if(member==null){
            //不是会员 自动注册会员
            member=new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(DateUtils.parseDate2String(new Date()));
            memberService.add(member);
        }
        //登录成功 向客户端返回cookie
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*7);
        response.addCookie(cookie);

        //保存信息进入redis
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone,60*60*24,json);

        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }

}
